<template>
	<div>
		<jk-table
			ref="xsNoticeMachine"
			:radio-config="{trigger: 'row'}"
			class="width-100-percent"
			:data="tableData"
			border
			highlight-hover-row
			highlight-current-row
			:height="height"
		>
			<vxe-column :visible="pageType === 'add' || pageType === 'edit'" title="操作" align="center" field="code" :width="60">
				<template slot-scope="scope">
					<div class="flex-center">
						<el-button :disabled="scope.row.openingState > 1" size="mini" fixed="left" type="text" icon="el-icon-remove" @click="onRemoveBtn(scope)"></el-button>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="机台" align="left" field="machineName" :width="90">
				<template slot-scope="scope">
					<div class="flex-start-center">
						<jk-state-bar :state="scope.row.openingState" :show-text="false" :state-list="openStateList"></jk-state-bar>
						<span>{{ scope.row.machineName }}</span>
					</div>
				</template>
			</vxe-column>
			<vxe-column v-if="formData.id" title="开台状态" align="center" field="openingState" :width="80">
				<template slot-scope="scope">
					<jk-state-bar :state="scope.row.openingState" :state-list="openStateList"></jk-state-bar>
				</template>
			</vxe-column>
			<vxe-column :visible="showInputColor" :title="getColorInfoByProcess(processCode).inputName" align="left" field="code" :min-width="130">
				<template slot="header">
					<div class="flex-between-center">
						<span>{{ getColorInfoByProcess(processCode).inputName }}</span>
						<checkboxPopover
							v-if="pageType !== 'detail'"
							:font-size="12"
							icon="el-icon-edit"
							:border="false"
							size="mini"
							text-name=""
							:title="getColorInfoByProcess(processCode).inputName"
							:default-list.sync="inputColors"
							:option-list="inputColorList"
							@change="onBatchSetInputColorChange"
						></checkboxPopover>
					</div>
				</template>
				<template slot-scope="scope">
					<span v-if="pageType === 'detail'">{{ scope.row.inputTubeColorList ? scope.row.inputTubeColorList.map(x => x.name).join() : '' }}</span>
					<checkboxPopover
						v-else
						:disabled="setState(scope.row)"
						:font-size="12"
						size="mini"
						:title="getColorInfoByProcess(processCode).inputName"
						:default-list.sync="scope.row.inputTubeColorList"
						:option-list="inputColorList"
						@change="updateParentData"
					></checkboxPopover>
				</template>
			</vxe-column>
			<vxe-column :visible="showOutColor" :title="getColorInfoByProcess(processCode).outName" align="left" field="code" :min-width="130">
				<template slot="header">
					<div class="flex-between-center">
						<span>{{ getColorInfoByProcess(processCode).outName }}</span>
						<checkboxPopover
							v-if="pageType !== 'detail'"
							icon="el-icon-edit"
							text-name=""
							:font-size="12"
							size="mini"
							:border="false"
							:title="getColorInfoByProcess(processCode).outName"
							:default-list.sync="outColors"
							:option-list="outColorList"
							@change="onBatchSetOutColorChange"
						></checkboxPopover>
					</div>
				</template>
				<template slot-scope="scope">
					<span v-if="pageType === 'detail'">{{ scope.row.outputTubeColorList ? scope.row.outputTubeColorList.map(x => x.name).join() : '' }}</span>
					<checkboxPopover
						v-else
						:disabled="setState(scope.row)"
						:font-size="12"
						size="mini"
						:title="getColorInfoByProcess(processCode).outName"
						:default-list.sync="scope.row.outputTubeColorList"
						:option-list="outColorList"
						@change="updateParentData"
					></checkboxPopover>
				</template>
			</vxe-column>
			<vxe-column title="工艺单" align="left" field="code" :width="120">
				<template slot="header">
					<div class="flex-between-center">
						<span>品种工艺单</span>
						<span v-if="pageType !== 'detail'" class="link-style el-icon-edit" @click="onEditMachineTechnologyBtn({}, true)"></span>
					</div>
				</template>
				<template slot-scope="scope">
					<div class="link-style" @click="onEditMachineTechnologyBtn(scope, false)">
						<div v-if="setState(scope.row)">
							<span>{{ scope.row.specSheet && scope.row.specSheet.code ? '查看' : '无' }}</span>
						</div>
						<div v-else>
							<span class="item-gap">{{ scope.row.specSheet && scope.row.specSheet.code ? '查看' : '无' }}</span>
							<span :class="pageType === 'detail' ? 'el-icon-view' : 'el-icon-edit-outline'"></span>
						</div>
					</div>
				</template>
			</vxe-column>
			<vxe-column :title="processCode.toUpperCase() === 'CS' ? '定量(g/10m)' : '定量(g/m)'" align="left" field="name" :width="160">
				<template slot="header">
					<div class="flex-between-center">
						<span>{{ processCode.toUpperCase() === 'CS' ? '定量(g/10m)' : '定量(g/m)' }}</span>
						<el-popover
							placement="right"
							width="300"
							title="批量设置"
							trigger="click"
						>
							<!--工序为粗纱时，只显示克重-->
							<div v-if="processCode.toUpperCase() === 'CS'">
								<jk-number-input v-model="dlVal" placeholder="克重" size="small"></jk-number-input>
							</div>
							<div v-else class="flex-start-center">
								<jk-number-input v-model="dlVal" placeholder="克重" size="small"></jk-number-input>
								<span>~</span>
								<jk-number-input v-model="mcVal" placeholder="米长" size="small"></jk-number-input>
							</div>
							<div class="flex-center margin-top-10">
								<el-button type="primary" size="small" @click="onConfirmBtnOfDmPopover">确定</el-button>
							</div>
							<span v-if="pageType !== 'detail'" slot="reference" class="link-style el-icon-edit"></span>
						</el-popover>
					</div>
				</template>
				<template slot-scope="scope">
					<div>
						<span v-if="pageType === 'detail'" class="">{{ `${scope.row.gramWeight || 0}~${scope.row.meters || 0}` }}</span>
						<div v-else class="flex-start-center">
							<jk-number-input v-model="scope.row.specSheet.gramWeight" :disabled="setState(scope.row)" size="mini" placeholder="克重" @change="onGramWeightChange($event, scope)"></jk-number-input>
							<span>~</span>
							<jk-number-input v-model="scope.row.specSheet.meters" :disabled="setState(scope.row)" size="mini" placeholder="米长" @change="onMetersChange($event, scope)"></jk-number-input>
						</div>
					</div>
				</template>
			</vxe-column>
			<vxe-column :visible="showStartTime" title="开台时间" align="left" field="startSystemTime" :width="206">
				<template slot="header">
					<div class="flex-between-center">
						<span>开台时间</span>
						<el-popover
							placement="right"
							width="200"
							title="批量设置"
							trigger="click"
						>
							<div class="flex-start-center">
								<jk-date-picker v-model="dateVal" :clearable="false" type="datetime" size="small" style="width: 100%;" value-format="yyyy-MM-dd hh:mm:ss" placeholder="开台时间" />
							</div>
							<div class="flex-center margin-top-10">
								<el-button type="primary" size="small" @click="onConfirmBtnOfDatePopover">确定</el-button>
							</div>
							<span v-if="pageType !== 'detail'" slot="reference" class="link-style el-icon-edit"></span>
						</el-popover>
					</div>
				</template>
				<template slot-scope="scope">
					<!--<span>{{ scope.row.startSystemTime }}</span>-->
					<span v-if="pageType === 'detail'">{{ scope.row.startSystemTime }}</span>
					<el-date-picker v-else v-model="scope.row.startSystemTime" :disabled="setState(scope.row)" :clearable="false" type="datetime" size="mini" style="width: 100%;" value-format="yyyy-MM-dd hh:mm:ss" placeholder="开台时间" @change="onChangeOpenTime($event, scope)" />
				</template>
			</vxe-column>
			<vxe-column :visible="showChangeDate" title="开台表数(M)" align="right" field="startOutput" :min-width="120">
				<template slot-scope="scope">
					<span v-if="pageType === 'detail'">{{ scope.row.startOutput }}</span>
					<jk-number-input v-else v-model="scope.row.startOutput" :disabled="setState(scope.row)" :clearable="true" type="datetime" size="mini" style="width: 100%;" value-format="yyyy-MM-dd" placeholder="开台表数(M)" @change="updateParentData" />
				</template>
			</vxe-column>
			<vxe-column :visible="showChangeDate" title="开台能耗表数" align="right" field="startElectricEnergy" :min-width="110">
				<template slot-scope="scope">
					<span v-if="pageType === 'detail'">{{ scope.row.startElectricEnergy }}</span>
					<jk-number-input v-else v-model="scope.row.startElectricEnergy" :disabled="setState(scope.row)" :clearable="true" type="datetime" size="mini" style="width: 100%;" value-format="yyyy-MM-dd" placeholder="开台能耗表数" @change="updateParentData" />
				</template>
			</vxe-column>
		</jk-table>
		<modify-machine-technology-order-dialog
			:disabled="disabled"
			:process-code="processCode"
			:page-type="pageType"
			:form-data="editMachineTechnologyInfo"
			:dialog-state="machineTechnologyState"
			@on-visible-change="onVisibleChangeOfModifyMachineTechnologyDialog"
			@on-confirm="onConfirmOfModifyMachineTechnologyDialog"
		></modify-machine-technology-order-dialog>
	</div>
</template>
<script>
    import checkboxPopover from '../../../order/components/form-box/checkbox-popover';
    import modifyMachineTechnologyOrderDialog from '../../../productionNoticeOrder/components/modify-machine-technology-order-dialog';
    import { openStateList } from '../../../../../utils/jk/status-option-list';
    import getTubeColor from '../../../foreSpinPrd/foreSpinningPlan/components/form-box/get-tube-color';
    import {
        productionPrdNoticeMachineChangeGetMachineDataList
    } from '../../../../../api/production/xsOpen';
    import { formatTime } from '../../../../../utils/jk/jk-tool';

    export default {
        mixins: [getTubeColor],
        props: {
            inputColorList: {
                type: Array,
                default() {
                    return [];
                }
            },
            outColorList: {
                type: Array,
                default() {
                    return [];
                }
            },
            showInputColor: {
                type: Boolean,
                default: true
            },
            showOutColor: {
                type: Boolean,
                default: true
            },
            showChangeDate: {
                type: Boolean,
                default: true
            },
            showStartTime: {
                type: Boolean,
                default: true
            },
            processCode: {
                type: String,
                default: 'XS'
            },
            pageType: {
                type: String,
                default: ''
            },
            machineList: {
                type: Array,
                default() {
                    return [];
                }
            },
            formData: {
                type: Object,
                default() {
                    return {};
                }
            },
            height: {
                type: Number,
                default: 300
            }
        },
        components: {
            modifyMachineTechnologyOrderDialog,
            checkboxPopover
        },
        data() {
            return {
                inputColors: [],
                outColors: [],
                machineIdx: null,
                dlVal: null,
                mcVal: null,
                openStateList: openStateList,
                dateVal: '',
                changeDateVal: '',
                editMachineTechnologyInfo: {},
                machineTechnologyState: false,
                defaultSpecSheetInfo: {
                    'batchCode': '',
                    'code': '',
                    'dailyYield': null,
                    'efficiencyPercent': null,
                    'fixedLength': null,
                    'gramWeight': null,
                    'id': null,
                    'machineModelCode': '',
                    'machineModelId': null,
                    'machineModelName': '',
                    'meters': null,
                    'moistureRegain': null,
                    'numbers': null,
                    'processCode': '',
                    'processId': null,
                    'processName': '',
                    'productCode': '',
                    'productId': null,
                    'productModels': '',
                    'productName': '',
                    'specDate': '',
                    'specEmpId': null,
                    'specEmpName': '',
                    'specSheetParamList': [],
                    'spindleNum': 0
                },
                disabled: false,
                tableData: [],
                disabledMachineStateList: [4] // 属于这类机台状态的，禁止修改内容
            };
        },
        methods: {
            // 获取指定机台采集的仪表数据
            getGatherMachineDataRequest(selectDateTime, machineIds) {
                if (selectDateTime && machineIds && machineIds.length) {
                    return productionPrdNoticeMachineChangeGetMachineDataList({
                        machineIds: machineIds,
                        selectDateTime: selectDateTime
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res || [];
                            if (this.tableData) {
                                this.tableData.forEach(x => {
                                    resData.forEach(k => {
                                        if (x.machineId === k.machineId) {
                                            this.setMachineItemInfo(x, k);
                                        }
                                    });
                                });
                                this.updateParentData();
                            }
                        }
                    });
                }
            },
            setMachineItemInfo(x, k) {
                // 开台能耗表数，默认等于采集到的实时能耗
                this.$set(x, 'startElectricEnergy', k.currentElectricEnergy);
                this.$set(x, 'startSystemElectricEnergy', k.currentElectricEnergy);
                // 开台产量表数，默认等于采集到的实时产量
                this.$set(x, 'startOutput', k.currentOutput);
                this.$set(x, 'startSystemOutput', k.currentOutput);
                // 上次的产量和能耗
                this.$set(x, 'lastEndOutput', k.lastEndOutput);
                this.$set(x, 'lastEndElectricEnergy', k.lastEndElectricEnergy);

                this.$set(x, 'openSpinCount', k.spinCount - k.usedSpinCount);
                this.$set(x, 'usedSpinCount', k.usedSpinCount);
                this.$set(x, 'spinCount', k.spinCount);

                this.$set(x, 'startOutputKg', k.currentOutputKg);
                this.$set(x, 'startSystemOutputKg', k.currentOutputKg);
            },
            onChangeOpenTime(e, scope) {
                if (e) {
                    this.getGatherMachineDataRequest(e, [scope.row.machineId]);
                } else {
                    const k = {};
                    this.tableData.forEach(x => {
                        this.setMachineItemInfo(x, k);
                    });
                    this.updateParentData();
                }
            },
            setState(row) {
                let disabled = false;
                // 详情页直接禁止修改
                if (this.pageType === 'detail') {
                    disabled = true;
                } else {
                    disabled = row && row.openingState ? this.disabledMachineStateList.includes(row.openingState) : false;
                }
                return disabled;
            },
            onBatchSetInputColorChange() {
                this.tableData.forEach(x => {
                    if (!this.disabledMachineStateList.includes(x.openingState)) {
                        this.$set(x, 'inputTubeColorList', JSON.parse(JSON.stringify(this.inputColors)));
                    }
                });
                this.updateParentData();
            },
            onBatchSetOutColorChange() {
                this.tableData.forEach(x => {
                    if (!this.disabledMachineStateList.includes(x.openingState)) {
                        this.$set(x, 'outputTubeColorList', JSON.parse(JSON.stringify(this.outColors)));
                    }
                });
                this.updateParentData();
            },
            onConfirmOfModifyMachineTechnologyDialog(item) {
                if (this.isBatchSet) {
                    this.tableData.forEach(x => {
                        if (!this.disabledMachineStateList.includes(x.openingState)) {
                            this.$set(x, 'dailyYield', item.dailyYield);
                            this.$set(x, 'gramWeight', item.gramWeight);
                            this.$set(x, 'meters', item.meters);
                            this.$set(x, 'specSheet', item);
                        }
                    });
                } else {
                    if (!this.disabledMachineStateList.includes(this.tableData[this.machineIdx].openingState)) {
                        this.$set(this.tableData[this.machineIdx], 'dailyYield', item.dailyYield);
                        this.$set(this.tableData[this.machineIdx], 'specSheet', item);
                    }
                }
                this.machineTechnologyState = false;
                this.updateParentData();
            },
            onVisibleChangeOfModifyMachineTechnologyDialog(e) {
                this.machineTechnologyState = e;
            },
            onEditMachineTechnologyBtn(scope, isBatchSet) {
                this.disabled = scope && scope.row ? this.setState(scope.row) : false;
                this.isBatchSet = isBatchSet;
                if (isBatchSet) {
                    this.machineIdx = null;
                    this.editMachineTechnologyInfo = JSON.parse(JSON.stringify(this.defaultSpecSheetInfo));
                } else {
                    this.machineIdx = scope.rowIndex;
                    this.editMachineTechnologyInfo = scope.row.specSheet || {};
                    this.editMachineTechnologyInfo.machineId = scope.row.machineId;
                    this.editMachineTechnologyInfo.machineCode = scope.row.machineCode;
                    this.editMachineTechnologyInfo.machineName = scope.row.machineName;
                }
                this.machineTechnologyState = true;
            },
            onConfirmBtnOfDmPopover() {
                this.tableData.forEach(x => {
                    if (!this.disabledMachineStateList.includes(x.openingState)) {
                        this.$set(x, 'gramWeight', this.dlVal);
                        this.$set(x, 'meters', this.mcVal);
                        this.$set(x.specSheet, 'gramWeight', this.dlVal);
                        // 工序为粗纱时，只允许修改克重
                        if (this.processCode.toUpperCase() !== 'CS') {
                            this.$set(x.specSheet, 'meters', this.mcVal);
                        }
                    }
                });
                this.updateParentData();
            },
            // 批量输入翻改日期
            onConfirmBtnOfChangeDatePopover() {
                this.tableData.forEach(x => {
                    if (!this.disabledMachineStateList.includes(x.openingState)) {
                        this.$set(x, 'changeDate', this.changeDateVal);
                    }
                });
                this.updateParentData();
            },
            onConfirmBtnOfDatePopover() {
                this.tableData.forEach(x => {
                    if (!this.disabledMachineStateList.includes(x.openingState)) {
                        this.$set(x, 'startSystemTime', this.dateVal);
                        this.getGatherMachineDataRequest(this.dateVal, this.tableData.map(x => x.machineId));
                    }
                });
                this.updateParentData();
            },
            onGramWeightChange(e, scope) {
                this.$set(this.tableData[scope.rowIndex], 'gramWeight', e);
                this.updateParentData();
            },
            onMetersChange(e, scope) {
                this.$set(this.tableData[scope.rowIndex], 'meters', e);
                this.updateParentData();
            },
            onRemoveBtn(scope) {
                this.tableData.splice(scope.rowIndex, 1);
                this.updateParentData();
            },
            updateParentData() {
                this.$emit('update:machineList', JSON.parse(JSON.stringify(this.tableData)));
                this.$emit('update', JSON.parse(JSON.stringify(this.tableData)));
            }
        },
        watch: {
            machineList: {
                handler(newVal) {
                    this.tableData = JSON.parse(JSON.stringify(newVal));
                },
                deep: true,
                immediate: true
            }
        }
    };
</script>
